import 'dart:convert';
import 'dart:ffi';
import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/bean/user.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/app_response.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/jmessage_helper.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/enter/view/main_page.dart';
import 'package:yuan_hang_app/views/mine/edit_pass_page.dart';
import 'package:yuan_hang_app/widget/common_dialog.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';
import 'package:yuan_hang_app/widget/webview_page.dart';

///登录页面
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<LoginPage> with WidgetsBindingObserver {
  final TextEditingController _useController =
      TextEditingController.fromValue(const TextEditingValue(text: "")); //
  final TextEditingController _passController =
      TextEditingController.fromValue(const TextEditingValue(text: ""));
  bool enable = false; //是否填写完整
  bool isPassword = false; //是否密码有内容
  bool canSeePass = true; //是否查看密码
  bool clearShow = false;
  bool showLoading = false;
  bool isCheck = false;
  final FocusNode _passFocus = FocusNode();
  final FocusNode _userFocus = FocusNode();
  final ScrollController _controller = ScrollController();
  bool isUserFocus = false;
  bool isPassFocus = false;

  @override
  void initState() {
    super.initState();
    _useController.text = SpUtil.getString(WConstant.username) ?? "";
    _passController.text = SpUtil.getString(WConstant.password) ?? "";
    setState(() {});
    _userFocus.addListener(() {
      if (_userFocus.hasFocus) {
        _scrollToBottom();
      }
    });
    _passFocus.addListener(() {
      if (_passFocus.hasFocus) {
        _scrollToBottom();
      }
    });

    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeMetrics() {
    // TODO: implement didChangeMetrics
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (Platform.isAndroid) {
        if (_userFocus.hasFocus) {
          if (_controller.position.maxScrollExtent >
              MediaQuery.of(context).viewInsets.bottom) {
            isUserFocus = true;
            isPassFocus = false;
          }
        } else if (_passFocus.hasFocus) {
          if (_controller.position.maxScrollExtent >
              MediaQuery.of(context).viewInsets.bottom) {
            isPassFocus = true;
            isUserFocus = false;
          }
        }
        if (isUserFocus &&
            !isPassFocus &&
            MediaQuery.of(context).viewInsets.bottom == 0) {
          _userFocus.unfocus();
          isUserFocus = false;
        }
        if (!isUserFocus &&
            isPassFocus &&
            MediaQuery.of(context).viewInsets.bottom == 0) {
          _passFocus.unfocus();
          isPassFocus = false;
        }
      }
    });
  }

  void _scrollToBottom() {
    var offset = _controller.position.maxScrollExtent -
        MediaQuery.of(context).viewInsets.bottom;
    if (offset == 0) {
      offset = 55.px;
    } else {
      offset = offset + 20.px;
    }

    _controller.animateTo(
      offset,
      curve: Curves.easeOut,
      duration: const Duration(milliseconds: 500),
    );
  }

  unFocus(BuildContext mContext) {
    final otherNode = FocusNode();
    FocusScope.of(mContext).requestFocus(otherNode);
    otherNode.unfocus();
  }

  @override
  Widget build(BuildContext mContext) {
    return PopScope(
      canPop: false, // 允许返回
      child: FullBasePage(
          hideNavi: true,
          resizeToBottomInset: true,
          statusStyleDark: true,
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              unFocus(context);
            },
            child: SingleChildScrollView(
              controller: _controller,
              physics: const BouncingScrollPhysics(),
              //padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
              //   padding: EdgeInsets.only(bottom:_userFocus.hasFocus || _passFocus.hasFocus? 500.px:0),
              child: Column(
                children: <Widget>[
                  SizedBox(
                    height: 80.px,
                  ),
                  Image.asset(
                    "images/logo_login.png",
                    width: 150.px,
                  ),
                  GestureDetector(
                    // onLongPress: () {
                    //   if (WConstant.MODEL_INT == 0) {
                    //     WConstant.MODEL_INT = 1;
                    //     Toast.toast("您已切换至uat正式环境");
                    //   } else if (WConstant.MODEL_INT == 1) {
                    //     WConstant.MODEL_INT = 2;
                    //     Toast.toast("您已切换至正式环境");
                    //   }else if (WConstant.MODEL_INT == 2) {
                    //     WConstant.MODEL_INT = 0;
                    //     Toast.toast("您已切换至sit环境");
                    //   }
                    // },
                    child: Container(
                        margin: EdgeInsets.only(left: 24.px),
                        alignment: Alignment.centerLeft,
                        child: WText(
                          "欢迎登录远航汽车",
                          style: TextStyle(
                            color: WColors.mainTextColor,
                            fontSize: 18.px,
                          ),
                        )),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10.px),
                    padding: EdgeInsets.symmetric(horizontal: 24.px),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          height: 56.px,
                          alignment: Alignment.centerLeft,
                          child: TextField(
                            keyboardAppearance: Brightness.light,
                            autofocus: true,
                            maxLength: 20,
                            focusNode: _userFocus,
                            onTap: () {
                              // _controller.jumpTo( _controller.position.maxScrollExtent);
                              setState(() {
                                FocusScope.of(context).requestFocus(_userFocus);
                              });
                            },
                            controller: _useController,
                            onChanged: (s) {
                              setState(() {
                                if (s.isNotEmpty &&
                                    _passController.text.isNotEmpty) {
                                  enable = true;
                                } else {
                                  enable = false;
                                }
                                clearShow = s.isNotEmpty ? true : false;
                              });
                            },
                            keyboardType: TextInputType.text,
                            decoration: InputDecoration(
                              counterText: "",
                              prefixIcon: const Icon(
                                Icons.person_outline_sharp,
                                color: WColors.C8A8A8A,
                              ),
                              suffix: Offstage(
                                  offstage: !clearShow,
                                  child: GestureDetector(
                                      onTap: () {
                                        _useController.clear();
                                        setState(() {
                                          clearShow = false;
                                          enable = false;
                                        });
                                      },
                                      child: Image.asset(
                                          'images/ic_del_grey.png',
                                          width: 16.px,
                                          height: 16.px))),
                              border: InputBorder.none,
                              enabledBorder: const UnderlineInputBorder(
                                  borderSide: BorderSide(
                                color: WColors.border,
                                width: 1,
                              )),
                              focusedBorder: const UnderlineInputBorder(
                                  borderSide: BorderSide(
                                color: WColors.primaryColor,
                                width: 1,
                              )),
                              hintText: "请输入账号",
                              hintStyle: TextStyle(
                                  color: WColors.CCCCCCC,
                                  fontSize: 14.px,
                                  height: 1),
                            ),
                          ),
                        ),
                        Container(
                          height: 56.px,
                          width: SizeUtils.screenWidthPX() - 48.px,
                          alignment: Alignment.centerLeft,
                          child: Row(
                            children: <Widget>[
                              Expanded(
                                  child: TextField(
                                obscureText: canSeePass,
                                controller: _passController,
                                focusNode: _passFocus,
                                style: TextStyle(
                                    color: WColors.mainTextColor,
                                    fontSize: 14.px,
                                    fontFamily: ''),
                                onChanged: (s) {
                                  setState(() {
                                    if (s.isNotEmpty &&
                                        _useController.text.isNotEmpty) {
                                      enable = true;
                                    } else {
                                      enable = false;
                                    }
                                  });
                                },
                                keyboardType: TextInputType.text,
                                inputFormatters: <TextInputFormatter>[
                                  LengthLimitingTextInputFormatter(20)
                                  //限制长度
                                ],
                                onTap: () {
                                  //    _controller.jumpTo( _controller.position.maxScrollExtent);
                                  setState(() {
                                    FocusScope.of(context)
                                        .requestFocus(_passFocus);
                                  });
                                },
                                decoration: InputDecoration(
                                  prefixIcon: const Icon(
                                    Icons.lock_outlined,
                                    color: WColors.C8A8A8A,
                                  ),
                                  border: InputBorder.none,
                                  hintText: "请输入密码",
                                  hintStyle: TextStyle(
                                      color: WColors.CCCCCCC,
                                      fontSize: 15.px,
                                      height: 1.0),
                                ),
                              )),
                              GestureDetector(
                                onTap: () {
                                  setState(() {
                                    canSeePass = !canSeePass;
                                  });
                                },
                                child: Image.asset(
                                  "images/${canSeePass ? 'ic_pass_close' : 'ic_pass_open'}.png",
                                  width: 18.px,
                                  height: 18.px,
                                ),
                              )
                            ],
                          ),
                        ),
                        WLine(
                          color: _passFocus.hasFocus
                              ? WColors.primaryColor
                              : WColors.border,
                          height: 1.px,
                        )
                      ],
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      CommonUtils.throttle(login);
                    },
                    child: Container(
                      margin: EdgeInsets.only(
                          top: 32.px, left: 24.px, right: 24.px),
                      alignment: Alignment.center,
                      height: 48.px,
                      decoration: BoxDecoration(
                        color: WColors.primaryColor,
                        borderRadius: BorderRadius.circular(24.px),
                      ),
                      child: WText(
                        "登录",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.px,
                        ),
                      ),
                    ),
                  ),
                  Container(
                      margin: EdgeInsets.only(
                          left: 24.px,
                          top: 18.px,
                          bottom: MediaQuery.of(context).viewInsets.bottom),
                      child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            GestureDetector(
                              onTap: () {
                                isCheck = !isCheck;
                                setState(() {});
                              },
                              child: Image.asset(
                                "images/${isCheck ? 'ic_login_check_s' : 'ic_login_check'}.png",
                                width: 20.px,
                                color: isCheck
                                    ? WColors.primaryColor
                                    : WColors.hintTextColor,
                              ),
                            ),
                            SizedBox(
                              width: 5.px,
                            ),
                            RichText(
                                text: TextSpan(children: [
                              TextSpan(
                                  text: "登录即代表同意远航汽车",
                                  style: TextStyle(
                                      fontSize: 12.px,
                                      color: WColors.hintTextColor)),
                              TextSpan(
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      print('点击文字');
                                      RouteHelper.pushWidget(
                                          context,
                                          WebViewPage(
                                              url:
                                                  "https://cms-minio.dayunauto.com:19010/dydata/user_service_agreement.html",
                                              title: "用户服务协议"));
                                    },
                                  text: "《用户服务协议》",
                                  style: TextStyle(
                                      fontSize: 12.px,
                                      color: WColors.primaryColor)),
                            ])),
                            // WText('登录即代表同意远航汽车',
                            //     style: TextStyle(
                            //         fontSize: WDimens.tsSmall,
                            //         color: WColors.primaryColor)),
                            // GestureDetector(
                            //     onTap: () {
                            //       /// 注册协议
                            //     },
                            //     child: Container(
                            //         padding:
                            //             EdgeInsets.symmetric(vertical: 12.px),
                            //         child: WText('《用户服务协议》',
                            //             style: TextStyle(
                            //                 fontSize: WDimens.tsSmall,
                            //                 color: WColors.primaryColor))))
                          ]))
                ],
              ),
            ),
          )),
      onPopInvoked: (didPop) {
        if (didPop) {
          return;
        }
        CommonDialog.showConformDialog(
            context: context,
            title: "提示",
            content: "你确认退出应用吗？",
            onConfirm: (text) {
              SystemNavigator.pop();
            });
      },
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    _controller.dispose();
  }

  void login() async {
    if (!isCheck) {
      Toast.toast("请先勾选用户服务协议");
      return;
    }
    if (_useController.text.isEmpty) {
      Toast.toast("请输入用户名");
      return;
    }
    if (_passController.text.isEmpty) {
      Toast.toast("请输入密码");
      return;
    }
    String password = await StringUtils.getRSAPassword(_passController.text);
    Toast.showLoading();
    HttpUtils().post(Api.login, data: {
      "appId": "YH",
      "username": _useController.text,
      "password": password,
    }).then((value) {
      if (value.resultCode == 200) {
        SpUtil.putString(WConstant.token, value.data["jwt"] ?? "");
        SpUtil.putInt(WConstant.userId, value.data["userId"] ?? 0);
        var userId = value.data["userId"];

        HttpUtils().get(Api.needChangePwd).then((value) {
          if (value.resultCode == 200) {
            if (value.data != null && value.data["data"] == 10041001) {
              //需要强制修改密码
              RouteHelper.pushReplacement(
                  context, const EditPassPage(isForceChange: true));
            } else {
              //不需要强制修改密码
              SpUtil.putString(WConstant.username, _useController.text);
              SpUtil.putString(WConstant.password, _passController.text);
              JmessageHelper.setAlias(
                  StringUtils.safeGetValue(userId, placeHolder: "0"));
              CommonReqUtils.getDictList().then((res) {
                WConstant.initList();
              });
              getUserInfo();
            }
          }
        });
      } else {
        Toast.toast(value.errMsg);
      }
    }).catchError((err) {
      Toast.dismissLoading();
    });
  }

  void getUserInfo() {
    HttpUtils().get(Api.getUserInfo).then((value) {
      Toast.dismissLoading();
      if (value.resultCode == 200) {
        SpUtil.putString(WConstant.USERINFO, json.encode(value.data));
        RouteHelper.pushReplacement(context, const MainPage());
      } else {
        Toast.toast(value.errMsg);
      }
    }).catchError((e) {
      Toast.dismissLoading();
    });
  }
}
